package com.munichosica.myapp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.munichosica.myapp.dao.CategoriaDao;
import com.munichosica.myapp.dto.Categoria;
import com.munichosica.myapp.exceptions.CategoriaDaoException;

public class CategoriaDaoImpl implements CategoriaDao{
	private StringBuilder sql=null;
	private StringBuilder sqlSelect=null; 
	public CategoriaDaoImpl(){
		sql=new StringBuilder();
		sqlSelect=new StringBuilder();
		sqlSelect.append("SELECT CATCODIGO_I, CATNOMBRE_V, CATABREV_C, CATESTADO_C, CATUSUARIOREGISTRA_V, CATFECHAREGISTRA_F, CATUSUARIOACTUALIZA_V, CATFECHAACTUALIZA_F FROM CATEGORIA ");
		
	}
	
	@Override
	public List<Categoria> listarPorCriterio(String criterio, String texto,String estado) throws CategoriaDaoException {
		
		sql.append("SELECT CATCODIGO_I, CATNOMBRE_V, CATABREV_C, CATESTADO_C, CATUSUARIOREGISTRA_V " +
				"FROM CATEGORIA WHERE CATEGORIA.CATESTADO_C LIKE '%"+estado.trim()+"%'");
		if(!criterio.isEmpty()) sql.append(" AND "+criterio.trim()+" LIKE '%"+texto.trim()+"%'");		
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		///System.out.print(sql);
		List <Categoria> lista=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sql.toString());
			boolean results=stmt.execute();
			if(results){
				lista=new ArrayList<Categoria>();
				rs=stmt.getResultSet();
				Categoria categoria=null;
				while(rs.next()){
					categoria=new Categoria();
					categoria.setCatcodigoI(rs.getInt("CATCODIGO_I"));
					categoria.setCatnombreV(rs.getString("CATNOMBRE_V"));
					categoria.setCatabrevC(rs.getString("CATABREV_C"));
					categoria.setCatestadoC(rs.getString("CATESTADO_C"));
					categoria.setCatusuarioregistraV(rs.getString("CATUSUARIOREGISTRA_V"));
					lista.add(categoria);					
				}				
			}
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
	return lista;
	}

	@Override
	public Categoria insertar(Categoria categoria) throws CategoriaDaoException {
		
		sql.append("INSERT INTO  categoria (catnombre_v ,catabrev_c ,catestado_c ,catusuarioregistra_v ,catfecharegistra_f )" +
				"VALUES (?,?,?,?,curdate() )");
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {conn=ResourceManager.getConnection();
		stmt=conn.prepareStatement(sql.toString(),PreparedStatement.RETURN_GENERATED_KEYS);
		stmt.setString(1, categoria.getCatnombreV());
		stmt.setString(2, categoria.getCatabrevC());
		stmt.setString(3, categoria.getCatestadoC());
		stmt.setString(4, categoria.getCatusuarioregistraV());		
		int results=stmt.executeUpdate();
		if(results>0){
			rs=stmt.getGeneratedKeys();
			if(rs.next()){
				categoria.setCatcodigoI(rs.getInt(1));
			}
		}
			
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return categoria;
	}

	@Override
	public Categoria modificar(Categoria categoria) throws CategoriaDaoException {
		sql.append(" UPDATE CATEGORIA SET CATNOMBRE_V =?, CATABREV_C =?,CATESTADO_C =?," +
				" CATUSUARIOACTUALIZA_V =?, CATFECHAACTUALIZA_F =curdate()" +
				" WHERE CATCODIGO_I =?");
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sql.toString());
			
			stmt.setString(1, categoria.getCatnombreV());
			stmt.setString(2, categoria.getCatabrevC());
			stmt.setString(3, categoria.getCatestadoC());
			stmt.setString(4, categoria.getCatusuarioregistraV());			
			stmt.setInt(5, categoria.getCatcodigoI());
			stmt.executeUpdate();
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return categoria;
	}

	@Override
	public Categoria obtener(Integer codigo) throws CategoriaDaoException  {
		sqlSelect.append(" WHERE CATCODIGO_I =?");
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		Categoria categoria=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sqlSelect.toString());
			stmt.setInt(1, codigo);
			boolean results=stmt.execute();
			if(results){				
				rs=stmt.getResultSet();				
				while(rs.next()){
					categoria=new Categoria();
					categoria.setCatcodigoI(rs.getInt("CATCODIGO_I"));
					categoria.setCatnombreV(rs.getString("CATNOMBRE_V"));
					categoria.setCatabrevC(rs.getString("CATABREV_C"));
					categoria.setCatestadoC(rs.getString("CATESTADO_C"));
					categoria.setCatusuarioregistraV(rs.getString("CATUSUARIOREGISTRA_V"));
								
				}				
			}
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return categoria;
	}

	@Override
	public Categoria eliminar(Categoria categori) throws CategoriaDaoException  {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Categoria> listarTodos() throws CategoriaDaoException {
		sqlSelect.append("WHERE CATESTADO_C != 'I'");
		List <Categoria> lista=null;
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sqlSelect.toString());
			boolean results=stmt.execute();
			if(results){
				lista=new ArrayList<Categoria>();
				rs=stmt.getResultSet();
				Categoria categoria=null;
				while(rs.next()){
					categoria=new Categoria();
					categoria.setCatcodigoI(rs.getInt("CATCODIGO_I"));
					categoria.setCatnombreV(rs.getString("CATNOMBRE_V"));
					categoria.setCatabrevC(rs.getString("CATABREV_C"));
					categoria.setCatestadoC(rs.getString("CATESTADO_C"));
					lista.add(categoria);					
				}				
			}
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return lista;
	}

	@Override
	public String codigoBarra(Integer codigo) throws CategoriaDaoException {
		sql.append("SELECT CONCAT(TRIM(CAT.CATABREV_C),RIGHT(CONCAT('000',CAST((COUNT(PRO.CATCODIGO_I)+1) AS CHAR(3))),3)) BARCODE " +
				"FROM CATEGORIA CAT " +
				"LEFT JOIN PRODUCTO PRO ON PRO.CATCODIGO_I=CAT.CATCODIGO_I " +
				"WHERE CAT.CATCODIGO_I=?");
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sql.toString());
			stmt.setInt(1, codigo);
			boolean results=stmt.execute();
			if(results){
				rs=stmt.getResultSet();
				if(rs.next()){
					return rs.getString("BARCODE");
				}
			}
		} catch (SQLException e) {
			throw new CategoriaDaoException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return null;
	}

}
